/**
 * @file 快捷键获取 Composable
 * @description 提供类型安全的快捷键获取方法，避免手动拼接字符串导致的错误
 * @author AI Assistant
 * @version 1.0.0
 */

import { computed, type ComputedRef } from 'vue'
import { shortcutsState } from '@/stores/globalState'
import type { CommandId } from '~types/global-state'
import { getEffectiveShortcuts } from '~shared/utils/shortcuts'
import { formatShortcutForDisplay } from '@/utils/shortcutFormat'

/**
 * 快捷键映射表类型
 */
type ShortcutMap = Map<CommandId, string>

/**
 * 创建快捷键映射表
 */
function createShortcutMap(): ComputedRef<ShortcutMap> {
  return computed(() => {
    const map = new Map<CommandId, string>()
    const list = getEffectiveShortcuts(shortcutsState.state?.overrides)

    for (const shortcut of list) {
      if (shortcut.id && shortcut.key && shortcut.enabled !== false) {
        map.set(shortcut.id, shortcut.key)
      }
    }

    return map
  })
}

/**
 * 获取单个快捷键
 * @param commandId 命令ID
 * @returns 快捷键字符串（如果未找到或未启用则返回空字符串）
 */
export function useShortcut(commandId: CommandId): ComputedRef<string> {
  const shortcutMap = createShortcutMap()

  return computed(() => {
    const raw = shortcutMap.value.get(commandId) || ''
    return formatShortcutForDisplay(raw)
  })
}

/**
 * 获取多个快捷键
 * @param commandIds 命令ID数组
 * @returns 快捷键映射对象
 */
export function useShortcuts<T extends readonly CommandId[]>(
  commandIds: T
): ComputedRef<Record<T[number], string>> {
  const shortcutMap = createShortcutMap()

  return computed(() => {
    const result: Record<string, string> = {}

    for (const id of commandIds) {
      const raw = shortcutMap.value.get(id) || ''
      result[id] = formatShortcutForDisplay(raw)
    }

    return result as Record<T[number], string>
  })
}

/**
 * 获取完整的快捷键映射表
 * @returns 快捷键映射表
 */
export function useShortcutMap(): ComputedRef<ShortcutMap> {
  return createShortcutMap()
}
